<!--
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2024-11-08 22:08:34
 * @LastEditTime: 2024-11-21 09:53:35
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 
 * @FilePath: \markdown-magic\src\pages\Pdf\page\entry\editor\index.vue
 * Copyright 版权声明
-->
<template>
  <div class="pageWrap">
    <a-spin :tip="spinningConfig.tip" :spinning="spinningConfig.spinning">
      <div v-show="fileList.length === 0">
        <div class="descArea">
          编辑 PDF文件的在线编辑器
        </div>
        <a-upload-dragger
          v-model:fileList="fileList"
          accept=".pdf,.PDF"
          name="file"
          :maxCount="1"
          :multiple="false"
          :showUploadList="false"
          action=""
          :before-upload="beforeUpload"
          :customRequest="customRequest"
          list-type="picture"
          @change="handleChange"
          @drop="handleDrop"
          @remove="handleRemove"
        >
          <p class="ant-upload-drag-icon">
            <inbox-outlined></inbox-outlined>
          </p>
          <p class="ant-upload-text">点击选择或拖拽文件到这里上传</p>
          <p class="ant-upload-hint">
            支持pdf格式的文件；最大支持1024MB
          </p>
        </a-upload-dragger>
      </div>
      <MainComp v-if="mergePdfData" :pdfData="mergePdfData"></MainComp>
    </a-spin>
  </div>
</template>

<script setup>
import { ref, reactive, defineEmits, computed } from 'vue'
import { message } from 'ant-design-vue'
import { PDFDocument } from 'pdf-lib'

import dayjs from 'dayjs'

import MainComp from './components/Main.vue'

const emit = defineEmits([])

// loading 配置
const spinningConfig = reactive({
  spinning: false,
  tip: '处理中...'
})

const fileList = ref([])

const mergedPdf = ref(null)

const mergePdfData = ref(null)

const handleRemove = (file) => {
  return false
}

const handleChange = (info) => {
  const status = info.file.status
  if (status === 'uploading') {
  } else if (status === 'done') {
    message.success(`${info.file.name} 文件上传成功.`)
  } else if (status === 'error') {
    message.error(`${info.file.name} 文件上传错误.`)
  } else if (status === 'removed') {
    message.error(`${info.file.name} 文件删除成功.`)
  }
}
const handleDrop = (e) => {
  console.log(e)
}

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'application/pdf'
  if (!isJpgOrPng) {
    message.error('请上传pdf格式的文件!')
  }
  const isLt2M = file.size / 1024 / 1024 < 1000
  if (!isLt2M) {
    message.error('文件必须小于1024MB!')
  }
  file.processConfig = {
    status: '未编辑'
  }
  return isJpgOrPng && isLt2M
}

// 自定义上传
const customRequest = async ({ action, file, onSuccess, onError }) => {
  spinningConfig.spinning = true
  spinningConfig.tip = '上传中...'
  try {
    fileList.value.find(async (item, index) => {
      if (item.uid === file.uid) {
        item.status = 'done'
        // 初始化配置项
        item.processConfig = {
          status: '未编辑'
        }

        const startTime = new Date()
        // 创建一个新的 PDF 文档
        mergedPdf.value = await PDFDocument.create();
        
        // 读取文件
        const reader = new FileReader();
        reader.onload = async function (e) {
          // 你可以在这里处理二进制内容
          const arrayBuffer = this.result;
    
          item.arrayBuffer = arrayBuffer
    
          let existingPdf = null
          try {
            // 加载现有的 PDF 文档
            existingPdf = await PDFDocument.load(arrayBuffer);
          } catch (error) {
            message.error(`文件【${item.name}】有密码保护，无法解析，无法合并！`)
            // 关闭loading
            spinningConfig.spinning = false
          }
          if (existingPdf === null) {
            fileList.value.splice(index, 1)
            return
          }
    
          // 获取所有页面
          item.existingPdf = existingPdf
          item.pages = existingPdf.getPages();
          item.pageCount = existingPdf.getPageCount();
          
          console.log(`🚀 ~ item:`, item)

          
          // 获取所有页面
          const pages = item.pages
          
          // 遍历每一页
          for (const ii in pages) {

            // 当前是第一页
            const currentPage = ii * 1 + 1
            
            // console.log(`🚀 ~ currentPage:`, currentPage)
            // console.log(`🚀 ~ item.processConfig.pageRange.start:`, item.processConfig.pageRange.start)
            // console.log(`🚀 ~ currentPage > item.processConfig.pageRange.end:`, item.processConfig.pageRange.end)

            const page = pages[ii]
            // 将页面复制到新的 PDF 文档中
            const copiedPage = await mergedPdf.value.copyPages(item.existingPdf, [ii])
            mergedPdf.value.addPage(copiedPage[0])
            
            console.log(`--------正在处理文件【${item.name}】的第${currentPage}页...------${dayjs().format('HH:mm:ss')}`)

            // 当前文档处理完毕后，更新状态
            if ((currentPage) === item.pageCount) {
              item.processConfig.status = '合并完成'
              console.log(`处理完成-----------文件【${item.name}】--------------共${item.pageCount}页---------------------${dayjs().format('HH:mm:ss')}`)
            }
      
            // 如果是最后一个文件 的 最后一页处理完后，关闭loading
            if ((currentPage) === item.pageCount) {
              mergePdfData.value = await mergedPdf.value.save()
              const endTime = new Date()
              const totalTime = (endTime - startTime) / 1000
              console.log(`---------------------------合并完成，共${item.pageCount}页，总耗时：${totalTime}秒`)
              spinningConfig.spinning = false
              message.success(`合并成功`)
              return
            }

          }
  
        }
    
        reader.readAsArrayBuffer(item.originFileObj);
        
        spinningConfig.spinning = false
      }
      return item.uid === file.uid
    })
  } catch (error) {
    // 关闭loading
    spinningConfig.spinning = false
    message.error(error)
  }
}
</script>

<style lang="scss" scoped>
.pageWrap{
  :deep(.ant-upload-wrapper .ant-upload-drag){
    height: auto !important;
  }
  .descArea{
    line-height: 1.6em;
    font-size: 14px;
    color: #666;
    margin-bottom: 12px;
  }
}
</style>